package com.registerserver.dao;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;


import com.registerserver.model.Teacher;

public class TeacherDaoImpl  implements TeacherDao{
	private Connection con;
	@Override
	public Teacher getTeacherInfo(String teacherID)  throws SQLException,IOException{
		
		String sql = "{call getTeacherInfoByID(?)}";
		if(con==null)
		{
			con=ConnectionFactory.createConnection();
		}
		CallableStatement call = con.prepareCall(sql);
		call.setString(1, teacherID);
		
		ResultSet result = call.executeQuery();
		Teacher teacher = new Teacher();
		if(result!=null)
		{
			while(result.next()){
				teacher.setID(result.getString("TeacherID"));
				teacher.setFirstName(result.getString("TeacherFirstName"));
				teacher.setLastName(result.getString("TeacherLastName"));
				teacher.setSex(result.getString("TeacherSex"));
				teacher.setBirthday(result.getDate("BirthDay"));
				teacher.setPosition(result.getString("Position"));
				teacher.setFacultyID(result.getString("FacultyID"));
			
			}
			return teacher;
				
		}
		
		return null;
	}

	@Override
	public boolean addNewTeacher(Teacher teacher) throws SQLException {
		String sql ="{call addNewTeacher('?','?','?','?','?','?','?')}";
		CallableStatement call = con.prepareCall(sql);
		call.setString(1, teacher.getID());
		call.setString(2, teacher.getFirstName());
		call.setString(3, teacher.getLastName());
		call.setString(4, teacher.getSex());
		call.setDate(5, (Date) teacher.getBirthday());
		call.setString(6, teacher.getPosition());
		call.setString(7, teacher.getFacultyID());
		
		return (call.executeUpdate()>0);
	}

	@Override
	public boolean deleteTeacher(String teacherID) throws SQLException {
		String sql = "{call deleteTeacherByID(?)}";
		CallableStatement call = con.prepareCall(sql);
		call.setString(1, teacherID);
		return (call.executeUpdate()>0);
	}

	@Override
	public boolean updateTeacherInfo(Teacher updateTeacher) throws SQLException {
		String sql = "{call updateTeacherInfo(?)}";
		CallableStatement call = con.prepareCall(sql);
		call.setString(1, updateTeacher.getID());
		call.setString(2, updateTeacher.getFirstName());
		call.setString(3, updateTeacher.getLastName());
		call.setString(4, updateTeacher.getSex());
		call.setDate(5, (Date) updateTeacher.getBirthday());
		call.setString(6, updateTeacher.getPosition());
		call.setString(7, updateTeacher.getFacultyID());
		return false;
	}

	
}
